import axios from 'axios';
import { ElNotification } from "element-plus";
import router from "@/router/index";

/**
 * 请求拦截器
 */
export const request = axios.create({
    timeout: 30000,
});

request.interceptors.request.use(config => {
    const token = localStorage.getItem('token');
    if (token) {
        return axios.post('/api/InterceptStatus', null, {
            headers: {
                Authorization: token
            }
        }).then(res => {
            if (res.data.code === 200) {
                config.headers.Authorization = token;
                return config;
            } else {
                ElNotification.error({
                    title: '登陆提示',
                    message: 'token状态异常或失效请重新登陆!'
                });
                router.push({ name: 'login' });
                return Promise.reject(new Error('Token invalid'));
            }
        }).catch(error => {
            ElNotification.error({
                title: '登陆提示',
                message: 'token状态异常或失效请重新登陆!'
            });
            router.push({ name: 'login' });
            return Promise.reject(error);
        });
    } else {
        ElNotification.error({
            title: '登陆提示',
            message: '无法验证token，请重新登陆!'
        });
        router.push({ name: 'login' });
        return Promise.reject(new Error('No token'));
    }
}, error => {
    return Promise.reject(error);
});
